package com.huawang.mdesign.model.service.model.property;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author cdl
 */
public class MeasurementContext {

    private static final ThreadLocal<MeasurementParam> CONTEXT = new InheritableThreadLocal<>();

    private MeasurementContext() {

    }

    public static void init() {
        CONTEXT.set(new MeasurementParam());
    }

    public static int getRecursiveCount() {
        return Optional.ofNullable(CONTEXT.get()).map(e -> {
            int recursiveCount = e.getRecursiveCount();
            e.setRecursiveCount(++recursiveCount);
            return recursiveCount;
        }).orElse(0);
    }

    public static void initMeasurementOfClass() {
        Optional.ofNullable(CONTEXT.get()).ifPresent(e -> {
            e.setFlag(false);
            e.setChanged(true);
        });
    }

    public static void initMeasurementOfDataType() {
        Optional.ofNullable(CONTEXT.get()).ifPresent(e -> e.setFlag(true));
    }

    public static boolean isFlag() {
        return Optional.ofNullable(CONTEXT.get()).map(MeasurementParam::isFlag).orElse(false);
    }

    public static boolean isChanged() {
        return Optional.ofNullable(CONTEXT.get()).map(MeasurementParam::isChanged).orElse(false);
    }

    @Nullable
    public static String getCurrentRoot() {
        return Optional.ofNullable(CONTEXT.get()).map(MeasurementParam::getCurrentRoot).orElse(null);
    }

    public static void setCurrentRoot(String currentRoot) {
        Optional.ofNullable(CONTEXT.get()).ifPresent(e -> e.setCurrentRoot(currentRoot));
    }

    @NotNull
    public static Map<String, String> getNameMap() {
        return Optional.ofNullable(CONTEXT.get()).map(MeasurementParam::getNameMap).orElse(new HashMap<>());
    }

    @NotNull
    public static Map<String, String> getNamespace() {
        return Optional.ofNullable(CONTEXT.get()).map(MeasurementParam::getNamespace).orElse(new HashMap<>());
    }

    @NotNull
    public static Map<String, List<String>> getPaths() {
        return Optional.ofNullable(CONTEXT.get()).map(MeasurementParam::getPaths).orElse(new HashMap<>());
    }

    public static void clear() {
        CONTEXT.remove();
    }
}
